package top.hmtools.jsCss.autoConfiguration;

import java.util.Iterator;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import top.hmtools.base.StringTools;

/**
 * 自动配置类，本jar包被其它spring boot 工程引用时的入口启动（初始化）程序
 * @author HyboJ
 * 创建日期：2017-9-26下午7:51:58
 */
@Configuration
@ComponentScan(basePackages={
        "top.hmtools.jsCss.cssManager",
        "top.hmtools.jsCss.jsManager",
        "top.hmtools.jsCss.srcManager"
        })
//@Import(value={IsEnableJsCss.class})
@ConditionalOnProperty(prefix = "hm_tools.js_css", value = "enabled", matchIfMissing = true) // 当配置文件中有hm_tools.js_css.enabled=false时，则不创建本类中的bean，如果为hm_tools.js_css.enabled=true，或者没有该条配置（注解默认为true），则创建bean
public class JsCssAutoConfiguration extends WebMvcConfigurerAdapter implements ApplicationContextAware{
	
private final Logger logger = LoggerFactory.getLogger(JsCssAutoConfiguration.class);
	
	private ApplicationContext applicationContext;

	public static final String prefix = "hm_tools.js_css.";

	/**
	 * 是否启用本jar包组件功能，当配置为“true”时或者不配置该值时均表示启用，为“false”时则不启用。
	 */
	public static final String enabled = prefix+"enabled";
	
	/**
	 * 配置获取javascript文件内容的请求uri
	 */
	public static final String js_uri = prefix+"js_uri";
	
	/**
	 * 配置获取CSS文件内容的请求uri
	 */
	public static final String css_uri=prefix+"css_uri";
	
	/**
	 * 配置刷新javascript文件缓存内容的请求uri
	 */
	public static final String refresh_js_uri=prefix+"refresh_js_uri";
	
	/**
	 * 配置刷新css文件缓存内容的请求uri
	 */
	public static final String refresh_css_uri=prefix+"refresh_css_uri";
	
	/**
	 * 配置获取javascript文件内容的磁盘路径集合，以英文逗号（,）分隔
	 */
	public static final String js_files_paths=prefix+"js_files_paths";
	
	/**
	 * 配置获取css文件内容的磁盘路径集合，以英文逗号（,）分隔
	 */
	public static final String css_files_paths=prefix+"css_files_paths";
	
	/**
	 * 获取的文件内容的字符编码格式名称，缺省为“UTF-8”
	 */
	public static final String encoding=prefix+"encoding";
	
	/**
	 * 获取所有javascript文件列表请求uri
	 */
	public static final String list_js_uri=prefix+"list_js_uri";
	
	/**
	 * 获取所有css文件列表请求uri
	 */
	public static final String list_css_uri=prefix+"list_css_uri";

	/**
	 * 通用获取静态资源请求uri
	 */
	public static final String src_uri = prefix+"src_uri";
	
	/**
	 * 缺省的静态资源路径集合
	 */
	private static final String DEFAULT_STATIC_PATHS = "static,resources";
	
	/**
	 * 通用获取静态资源请求uri
	 * @return
	 */
	public String getSrcUri(){
		return this.getProperty(src_uri, "/src");
	}

	/**
	 * @return the enabled
	 */
	public boolean getEnabled() {
		boolean result = true;
		String property = this.getProperty(enabled, String.valueOf(result));
		try {
			result = Boolean.getBoolean(property);
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * @return the jsUri
	 */
	public String getJsUri() {
		return this.getProperty(js_uri, "/js");
	}

	/**
	 * @return the cssUri
	 */
	public String getCssUri() {
		return this.getProperty(css_uri, "/css");
	}

	/**
	 * @return the refreshJsUri
	 */
	public String getRefreshJsUri() {
		String result = "/refresh/js";
		String tmp = this.getProperty(refresh_js_uri,"");
		if(StringTools.isNotBlank(tmp)){
			result=tmp;
		}
		return result;
	}

	/**
	 * @return the refreshCssUri
	 */
	public String getRefreshCssUri() {
		return this.getProperty(refresh_css_uri, "/refresh/css");
	}

	/**
	 * @return the jsFilesPaths
	 */
	public String getJsFilesPaths() {
		return this.getProperty(js_files_paths,DEFAULT_STATIC_PATHS);
	}

	/**
	 * @return the cssFilesPaths
	 */
	public String getCssFilesPaths() {
		return this.getProperty(css_files_paths,DEFAULT_STATIC_PATHS);
	}

	/**
	 * @return the encoding
	 */
	public String getEncoding() {
		return this.getProperty(encoding, "UTF-8");
	}

	/**
	 * @return the listJsUri
	 */
	public String getListJsUri() {
		return this.getProperty(list_js_uri,"/list/js");
	}

	/**
	 * @return the listCssUri
	 */
	public String getListCssUri() {
		return this.getProperty(list_css_uri, "/list/css");
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;
	}
	
	/**
	 * 根据配置键名获取配置值，如果没有，则使用缺省值。
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	private String getProperty(String key,String defaultValue){
		String result = this.applicationContext.getEnvironment().getProperty(key, defaultValue).trim();
		if(StringTools.isBlank(result)){
			result = defaultValue;
		}
		return result;
	}
	
	/**
     * 获取项目工程配置文件内容
    * <br>方法说明：                    getApplicationConfig
    * <br>输入参数说明：           
    * <br>@return
    * <br>输出参数说明：
    * <br>Properties           
    *
     */
    public Properties getApplicationConfig(){
        Properties result = new Properties();
        //applicationConfig
        if(this.applicationContext == null){
            return result;
        }
        MutablePropertySources propertySources = ((ConfigurableApplicationContext)this.applicationContext).getEnvironment().getPropertySources();
        Iterator<PropertySource<?>> iterator = propertySources.iterator();
        
        while (iterator.hasNext()) {
            PropertySource<?> ps = iterator.next();
            this.logger.info("PropertySource ==>>"+ps.toString());
            
            Object source = ps.getSource();
            if(Properties.class.isInstance(source)){
                this.logger.debug("成功加载配置信息："+source.toString());
                result.putAll((Properties)source);
            }
        }
        return result;
    }
    
    /**
     * 解决restFul URL 末尾小数点被忽略的方法之一
     */
    @Override
	public void configurePathMatch(PathMatchConfigurer configurer) {
//		configurer.setUseSuffixPatternMatch(false);
    	super.configurePathMatch(configurer);
	}
}
